package com.example.javamediaserver.rtmp;

import com.example.javamediaserver.config.MediaServerConfig;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

@Component
@RequiredArgsConstructor
@Slf4j
public class RtmpServer {

    private final MediaServerConfig config;
    private final RtmpHandlerFactory handlerFactory;
    
    private EventLoopGroup bossGroup;
    private EventLoopGroup workerGroup;
    private ChannelFuture serverChannel;
    
    @PostConstruct
    public void start() {
        try {
            bossGroup = new NioEventLoopGroup(1);
            workerGroup = new NioEventLoopGroup();
            
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 128)
                .childOption(ChannelOption.SO_KEEPALIVE, true)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) {
                        ch.pipeline().addLast(
                            handlerFactory.createHandlers()
                        );
                    }
                });
            
            // 绑定端口并启动服务器
            serverChannel = b.bind(config.getRtmp().getPort()).sync();
            log.info("RTMP服务器启动 (using Ant Media handlers)，端口: {}", config.getRtmp().getPort());
        } catch (Exception e) {
            log.error("启动RTMP服务器失败", e);
            shutdown();
        }
    }
    
    @PreDestroy
    public void shutdown() {
        log.info("关闭RTMP服务器...");
        
        if (serverChannel != null) {
            serverChannel.channel().close();
        }
        
        if (bossGroup != null) {
            bossGroup.shutdownGracefully();
        }
        
        if (workerGroup != null) {
            workerGroup.shutdownGracefully();
        }
    }
} 